<template>
  <a-drawer
      title="发票编辑"
      :visible="visible"
      :destroyOnClose="true"
      width="60%"
      :body-style="{ padding: '0px', height: 'calc(100% - 55px)' }"
      @close="onClose"
  >
    <section class="content">
      <a-form layout="vertical">
        <a-card :headStyle="cardHeadStyle">
          <template #title>
            发票信息
            <TextTip
                tips="编写完发票号码、发票日期，发票状态才会变成“已开票”。数电票，发票代码可以不填写。"
            />
          </template>
          <a-row :wrap="true" :gutter="[12, 12]">
            <a-col :span="8">
              <a-form-item label="发票号码">
                <a-input
                    placeholder="请输入发票号码"
                    v-model:value="formData.invoice_number"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="发票代码">
                <a-input
                    placeholder="请输入发票代码"
                    v-model:value="formData.invoice_code"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="开票日期">
                <a-date-picker
                    placeholder="请选择开票日期"
                    v-model:value="formData.invoice_time"
                    :disabled="invoiceDateDisabled"
                    :valueFormat="dateFormat"
                    class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item>
                <template #label>
                  电子发票地址
                  <TextTip
                      tips="可以将电子税局的发票二维码上传至此用于保存。"
                  />
                </template>

                <a-upload
                    :action="imgAction"
                    :multiple="false"
                    :headers="{ 'org-token': $store.getters.token }"
                    :file-list="fileList"
                    name="image"
                    :max-count="1"
                    accept="image/jpg,image/jpeg,image/gif,image/png"
                    @change="handleUploadChange"
                >
                  <a-button>
                    <upload-outlined></upload-outlined>
                    上传
                  </a-button>
                </a-upload>

              </a-form-item>
            </a-col>


          </a-row>
        </a-card>
        <a-card title="购方信息" :headStyle="cardHeadStyle" class="mt-20">
          <a-row :wrap="true" :gutter="[12, 12]">
            <a-col :span="8">
              <a-form-item label="公司名称">
                <a-input
                    placeholder="请输入公司名称"
                    v-model:value="formData.buyer_name"
                    disabled
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="纳税人识别号">
                <a-input
                    placeholder="请输入纳税人识别号"
                    v-model:value="formData.owner_taxpayerIdNumber"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="地址">
                <a-input
                    placeholder="请输入地址"
                    v-model:value="formData.owner_address"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="开户行">
                <a-input
                    placeholder="请输入开户行"
                    v-model:value="formData.owner_bank"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="账户">
                <a-input
                    placeholder="请输入账户"
                    v-model:value="formData.owner_account"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="电话">
                <a-input
                    placeholder="请输入电话"
                    v-model:value="formData.owner_tel"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="售方信息" :headStyle="cardHeadStyle" class="mt-20">
          <a-row :wrap="true" :gutter="[12, 12]">
            <a-col :span="8">
              <a-form-item label="公司名称">
                <a-select
                    v-model:value="formData.seller_id"
                    placeholder="请选择售方"
                    @change="onSellerChange"
                >
                  <a-select-option
                      v-for="item of sellerList"
                      :key="item.id"
                      :value="item.id"
                  >{{ item.company_name }}
                  </a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="纳税人识别号">
                <a-input
                    placeholder="请输入纳税人识别号"
                    v-model:value="formData.seller_taxpayerIdNumber"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="地址">
                <a-input
                    placeholder="请输入地址"
                    v-model:value="formData.seller_address"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="开户行">
                <a-input
                    placeholder="请输入开户行"
                    v-model:value="formData.seller_bank"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="账户">
                <a-input
                    placeholder="请输入账户"
                    v-model:value="formData.seller_account"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="电话">
                <a-input
                    placeholder="请输入电话"
                    v-model:value="formData.seller_tel"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="商品或服务明细" :headStyle="cardHeadStyle" class="mt-20">
          <a-alert show-icon>
            <template #message>
              <span>金额合计：</span>
              <span class="fw-bold">{{ invoiceTotal.price }}</span>
              <span> 元 </span>
              <span class="ml-10">税额合计：</span>
              <span class="fw-bold">{{ invoiceTotal.tax }}</span>
              <span> 元 </span>
              <span class="ml-10">价税合计：</span>
              <span class="fw-bold">{{ invoiceTotal.taxPrice }}</span>
              <span> 元 </span>
            </template>
          </a-alert>
          <a-table
              :dataSource="splitList"
              :columns="COLUMNS"
              :pagination="false"
              rowKey="key"
              class="mt-10"
          >
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'tax_rate'">
                {{ text }}%
              </template>
              <template v-if="column.key === 'specs'">
                <a-input
                    v-model:value="record.specs"
                    placeholder="请输入规格"
                    style="width: 120px"
                    :disabled="Number(record.apply_invoice_amount) == 0"
                />
              </template>
              <template v-if="column.key === 'invoice_unit'">
                <a-input
                    v-model:value="record.invoice_unit"
                    placeholder="请输入单位"
                    style="width: 120px"
                    :disabled="Number(record.apply_invoice_amount) == 0"
                />
              </template>
            </template>
          </a-table>
        </a-card>
        <a-card title="其他信息" :headStyle="cardHeadStyle" class="mt-20">
          <a-row :wrap="true" :gutter="[12, 12]">
             <a-col :span="24">
              <a-form-item label="附件">
                <a-upload-dragger
                  v-model:fileList="fileAnnexList"
                  name="file"
                  :multiple="true"
                  :action="$utils.fileAction"
                  :headers="{ 'org-token': $store.getters.token }"
                  @change="handleAnnexUploadChange"
                  @remove="removeAnnexUpload"
                  accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                  :data="{ dir: 'org_contract_add_attachments' }"
                >
                    <p class="ant-upload-drag-icon">
                      <InboxOutlined />
                    </p>
                    <p class="ant-upload-text">
                      拖拽文件至虚线款内或点击此区域上传文件
                    </p>
                    <p class="ant-upload-hint">文档只支持doc,docx,pdf,jpg,jpeg,png格式</p>
                </a-upload-dragger>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="备注">
                <a-textarea
                    placeholder="请输入备注"
                    v-model:value="formData.remark"
                    :rows="4"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </section>

    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {computed, defineComponent, reactive, toRaw, toRefs, watch, ref} from "vue";
import request from "../../../../common/utils/request";
import {TextTip} from "bl-common-vue3";
import {UploadOutlined,InboxOutlined} from "@ant-design/icons-vue";
import {message} from 'ant-design-vue'


export default defineComponent({
  name: "MakeInvoiceEdit",
  components: {TextTip, UploadOutlined,InboxOutlined},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    content: {
      type: Object,
      default: () => ({}),
    },
    editType: {
      type: Number,
      default: 1, // 1初始化进入 2编辑进入
    },
  },
  setup(props, {emit}) {
    const state = reactive({
      sellerList: [],
      splitList: [],
      invoiceTotal: {},
      invoiceList: [],
      fileAnnexList:[]
    });
    const fileList = ref([])

    const formData = reactive({
      file:[]
    });

    const invoiceDateDisabled = computed(
        () => !(formData.invoice_number)
    );

    const onSellerChange = (val) => {
      const current = state.sellerList.find((item) => item.id == val);
      setFormData({
        seller_taxpayerIdNumber: current.taxpayer_number,
        seller_tel: current.phone,
        seller_bank: current.bank,
        seller_account: current.bank_account,
        seller_address: current.address,
        seller_name:current.company_name
      });
    };

    const onClose = () => {
      emit("cancel");
    };
    const onSubmit = () => {
      if (formData.invoiceList) {
        formData.invoiceList.forEach((item) => {
          state.invoiceList.forEach((invoice) => {
            if (item.id == invoice.id) {
              item.tax_number = formData.owner_taxpayerIdNumber;
              item.tax_bank_name = formData.owner_bank;
              item.tax_bank_account = formData.owner_account;
              item.tax_company_address = formData.owner_address;
              item.tax_company_tel = formData.owner_tel;
            }
          });
        });
      }
      console.log("--------------edit submit", toRaw(formData));
      formData.editType = 2;
      setTimeout(() => {
        emit("success", formData);
      }, 20);
    };

    const setFormData = (state) => {
      for (let key in state) {
        formData[key] = state[key];
      }
      if (state.e_invoice_link) {
        fileList.value = [{"name": state.e_invoice_link}]
      }
    };

    // 获取售方列表
    const getSellers = () => {
      if (state.sellerList.length) {
        return;
      }
      request.get("/org", "/invoice/sellerList").then((res) => {
        state.sellerList = res.list;
      });
    };

    const isEdit = computed(
        () => props.editType == 2 || props.content.editType == 2
    );

    // 商品或服务的总计信息
    const getInvoiceTotal = () => {
      let taxTotal = 0,
          priceTotal = 0,
          taxPriceTotal = 0;
      state.splitList.forEach((item) => {
        taxTotal = (Number(taxTotal) + Number(item.tax_amount)).toFixed(2);
        priceTotal = (Number(priceTotal) + Number(item.unit_price)).toFixed(2);
        taxPriceTotal = (
            Number(taxPriceTotal) + Number(item.apply_invoice_amount)
        ).toFixed(2);
      });
      state.invoiceTotal = {
        tax: taxTotal,
        price: priceTotal,
        taxPrice: taxPriceTotal,
      };
    };
    
    const init = () => {
      const {content} = props;
      let data = {};
      if (content?.invoiceList?.length) {
        data = content.invoiceList.filter(
            (item) => item.id == content.title_id
        )[0];
        state.invoiceList = content.invoiceList.filter(
            (item) => item.id == content.title_id
        );
      }

      setFormData(content);
      setFormData({
        buyer_name: data.title||'',
        owner_taxpayerIdNumber: data.tax_number || "",
        owner_bank: data.tax_bank_name || "",
        owner_account: data.tax_bank_account || "",
        owner_address: data.tax_company_address || "",
        owner_tel: data.tax_company_tel || "",
      });
      if (!isEdit.value) {
        setFormData({
          seller_taxpayerIdNumber: content.seller_info.taxpayer_number,
          seller_tel: content.seller_info.phone,
          seller_bank: content.seller_info.bank,
          seller_account: content.seller_info.bank_account,
          seller_address: content.seller_info.address,
        });
      }
      getSellers();
      state.splitList = [];
      content.splitList.forEach((item, index) => {
        if (item.splitList && item.splitList.length) {
          // 合并状态下
          item.splitList.forEach((item2, index2) => {
            item2.key = `${index}-${index2}`;
            state.splitList.push(item2);
          });
        } else {
          // 不合并
          item.key = index;
          state.splitList.push(item);
        }
      });
      getInvoiceTotal();

      if (content?.file && content?.file.length > 0) {
        state.fileAnnexList = content.file
      } else {
        state.fileAnnexList = []
      }
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          }
        }
    );

    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      if (resFileList.length) {
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.name = file.response.data.text;
              formData.e_invoice_link = file.response.data.text;
            } else {
              file.name = "";
              message.warning(file.response.msg);
            }
          }
          return file;
        });
        fileList.value = resFileList.filter(file => {
          return file.name != "";
        })
      } else {
        fileList.value = [];
      }
      if (fileList.value.length == 0) {
        formData.e_invoice_link = "";
      }

    };

    const removeAnnexUpload = (file,) => {
      formData.file = formData.file.filter((item) => item.file != file.url)
    }

    const handleAnnexUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      }
      state.fileAnnexList = resFileList;
      formData.file = state.fileAnnexList.filter((itme) => itme.status == 'done')
    };

    return {
      formData,
      cardHeadStyle: {
        background: "#f7f7f7",
        fongWeight: "bold",
        color: "#000",
        fontSize: "14px",
      },
      invoiceDateDisabled,
      dateFormat: "YYYY-MM-DD",
      COLUMNS,
      ...toRefs(state),
      onSellerChange,
      onClose,
      onSubmit,
      fileList,
      handleUploadChange,
      imgAction: request.BASE_URL + "/public/qrcode/parse",
      handleAnnexUploadChange,
      removeAnnexUpload
    };
  },
});

const COLUMNS = [
  {
    title: "商品或服务名称",
    dataIndex: "tax_cost_name",
    key: "tax_cost_name",
  },
  {
    title: "规格型号",
    dataIndex: "specs",
    key: "specs",
    width: 100,
  },
  {
    title: "单位",
    dataIndex: "invoice_unit",
    key: "invoice_unit",
    width: 100,
  },
  {
    title: "数量",
    dataIndex: "total",
    key: "total",
  },
  {
    title: "单价",
    dataIndex: "unit_price",
    key: "unit_price",
  },
  {
    title: "金额",
    dataIndex: "nopay_tax_price",
    key: "nopay_tax_price",
  },
  {
    title: "税率",
    dataIndex: "tax_rate",
    key: "tax_rate",
  },
  {
    title: "税额",
    dataIndex: "tax_amount",
    key: "tax_amount",
  },
  {
    title: "价税合计",
    dataIndex: "apply_invoice_amount",
    key: "apply_invoice_amount",
  },
];
</script>

<style lang="less" scoped>
.content {
  height: 100%;
  padding: 20px 20px 80px 20px;
  overflow: hidden auto;
}
</style>
